package com.gd.deron.smartrobot.baobao.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.gd.deron.smartrobot.baobao.app.MyApplication;

import android.annotation.SuppressLint;

/**
 * Json结果解析类
 */
public class JsonParser {

	public static String parseIatResult(String json) {
		StringBuffer ret = new StringBuffer();
		try {
			JSONTokener tokener = new JSONTokener(json);
			JSONObject joResult = new JSONObject(tokener);

			JSONArray words = joResult.getJSONArray("ws");
			for (int i = 0; i < words.length(); i++) {
				// 转写结果词，默认使用第一个结果
				JSONArray items = words.getJSONObject(i).getJSONArray("cw");
				JSONObject obj = items.getJSONObject(0);
				ret.append(obj.getString("w"));
//				如果需要多候选结果，解析数组其他字段
//				for(int j = 0; j < items.length(); j++)
//				{
//					JSONObject obj = items.getJSONObject(j);
//					ret.append(obj.getString("w"));
//				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return ret.toString();
	}
	
	public static String parseGrammarResult(String json, String engType) {
		StringBuffer ret = new StringBuffer();
		try {
			JSONTokener tokener = new JSONTokener(json);
			JSONObject joResult = new JSONObject(tokener);

			JSONArray words = joResult.getJSONArray("ws");
			// 云端和本地结果分情况解析
			if ("cloud".equals(engType)) {
				for (int i = 0; i < words.length(); i++) {
					JSONArray items = words.getJSONObject(i).getJSONArray("cw");
					for(int j = 0; j < items.length(); j++)
					{
						JSONObject obj = items.getJSONObject(j);
						if(obj.getString("w").contains("nomatch"))
						{
							ret.append("没有匹配结果.");
							return ret.toString();
						}
						ret.append("【结果】" + obj.getString("w"));
						ret.append("【置信度】" + obj.getInt("sc"));
						ret.append("\n");
					}
				}
			} else if ("local".equals(engType)) {
				for (int i = 0; i < words.length(); i++) {
					JSONObject wsItem = words.getJSONObject(i);
					JSONArray items = wsItem.getJSONArray("cw");
					if ("<contact>".equals(wsItem.getString("slot"))) {
						// 可能会有多个联系人供选择，用中括号括起来，这些忙鿉项具有相同的置信度
						for(int j = 0; j < 1; j++)
						{
							JSONObject obj = items.getJSONObject(j);
							if(obj.getString("w").contains("nomatch"))
							{
								ret.append("没有匹配结果.");
								return ret.toString();
							}
							ret.append(obj.getString("w"));						
						}
					} else {
						//本地多忙鿉按照置信度高低排序，一般鿉取第一个结果即叿
						JSONObject obj = items.getJSONObject(0);
						if(obj.getString("w").contains("nomatch"))
						{
							ret.append("没有匹配结果.");
							return ret.toString();
						}
						ret.append(obj.getString("w"));						
					}
				}
			
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			ret.append("没有匹配结果.");
		} 
		return ret.toString();
	}
	
	public static String parseGrammarResultToInt(String json) {
		StringBuffer ret = new StringBuffer();
		try {
			JSONTokener tokener = new JSONTokener(json);
			JSONObject joResult = new JSONObject(tokener);

			JSONArray words = joResult.getJSONArray("ws");
			
				for (int i = 0; i < words.length(); i++) {
					
				ret.append(joResult.getInt("sc"));
				}
		} catch (Exception e) {
			e.printStackTrace();
			ret.append("没有匹配结果.");
		} 
		return ret.toString();
	}
	
	public static String parseGrammarResult(String json) {
		StringBuffer ret = new StringBuffer();
		try {
			JSONTokener tokener = new JSONTokener(json);
			JSONObject joResult = new JSONObject(tokener);

			JSONArray words = joResult.getJSONArray("ws");
			for (int i = 0; i < words.length(); i++) {
				JSONArray items = words.getJSONObject(i).getJSONArray("cw");
				for(int j = 0; j < items.length(); j++)
				{
					JSONObject obj = items.getJSONObject(j);
					if(obj.getString("w").contains("nomatch"))
					{
						ret.append("没有匹配结果.");
						return ret.toString();
					}
					ret.append("【结果】" + obj.getString("w"));
					ret.append("【置信度】" + obj.getInt("sc"));
					ret.append("\n");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ret.append("没有匹配结果.");
		} 
		return ret.toString();
	}
	
	public static String parseJsonToNluAnswer(String text) {
    	JSONObject dataJson = null;
    	String asnwerResult = null;
		try {
			dataJson = new JSONObject(text);
			//mUnderstanderText.setText(dataJson.toString());
			String service =  dataJson.getString("service");//语义场景
			String dataOrig = dataJson.getString("text");//提问
			
			if(dataOrig.contains("不听了")||dataOrig.contains("不问了")){
				return "close";
			}else if(dataOrig.contains("位置")||dataOrig.contains("在哪")){
				return "address";
			}else if(dataOrig.contains("故事")){
				return "tales";
			}else if(dataOrig.contains("古诗")||dataOrig.contains("诗")){
				return "ancient_poetry";
			}else if(dataOrig.contains("启蒙")||dataOrig.contains("英语启蒙")){
				return "initiation";
			}else if(dataOrig.contains("儿歌")){
				return "children_song";
			}else if(dataOrig.contains("天气")||dataOrig.contains("温度")||service.equals("weather")){//天气
				JSONObject data;
				try {
					JSONArray answer = dataJson.getJSONArray("moreResults");
					data = answer.getJSONObject(0).getJSONObject("data");
				} catch (Exception e) {
					 data = dataJson.getJSONObject("data");
				}
				JSONArray weatherdata = data.getJSONArray("result");
				//Log.e(TAG,"weatherdata长度="+weatherdata.length());
				JSONObject weatherObject = null;
				if(dataOrig.contains("明天"))
					weatherObject = weatherdata.getJSONObject(1);
				else if(dataOrig.contains("后天"))
					weatherObject = weatherdata.getJSONObject(2);
				else if(dataOrig.contains("大后天"))
					weatherObject = weatherdata.getJSONObject(3);
				else
					weatherObject = weatherdata.getJSONObject(0);
				
				String date  = convertTotime(getTimelong(weatherObject.getString("date")));
				String city = weatherObject.getString("city")+"的天气";
				String wind = weatherObject.getString("wind");
				String weather = weatherObject.getString("weather");
				String tempRange = "气温是"+weatherObject.getString("tempRange");
				try {
					String humidity = "湿度是" +weatherObject.getString("humidity");//湿度
					asnwerResult = date+","+city+","+wind+","+weather+","+tempRange+","+humidity;
				} catch (Exception e) {
					asnwerResult = date+","+city+","+wind+","+weather+","+tempRange;
				}
				return asnwerResult;
			}else if(service.equals("cookbook")){//菜谱
				JSONObject data = dataJson.getJSONObject("data");
				JSONArray cookbookdata = data.getJSONArray("result");
				JSONObject cookbook = cookbookdata.getJSONObject(0);
				String ingredient = "主要材料:"+cookbook.getString("ingredient");//主要材料
				String accessory = "辅助材料:"+cookbook.getString("accessory");//辅助材料
				asnwerResult = ingredient+","+accessory;
				//return asnwerResult;
				
			}else if(service.equals("pm25")){//空气质量
				JSONObject data = dataJson.getJSONObject("data");
				JSONArray pmdata = data.getJSONArray("result");
				JSONObject pm = pmdata.getJSONObject(0);
				String pm25 = "颗粒物为"+pm.getString("pm25");
				String aqi = "空气质量指数是"+pm.getString("aqi");//空气质量指数
				String quality = "空气质量是"+pm.getString("quality");//空气质量
				String area = pm.getString("area");
				String subArea = pm.getString("subArea");
				asnwerResult = area+subArea+quality+","+aqi+","+pm25;
				//return asnwerResult;
			}else if(service.equals("stock")){//股票
				JSONObject data = dataJson.getJSONObject("semantic");
				JSONObject stockdata = data.getJSONObject("slots");
				String category = stockdata.getString("category");//交易所
				if(category.toUpperCase().equals("SZ"))//深圳
					category = "深圳";
				else if(category.toUpperCase().equals("SH"))
					category = "上海";
				else if(category.toUpperCase().equals("HK"))
					category = "香港";
				String name = stockdata.getString("name");
				String code = stockdata.getString("code");
				asnwerResult = name + "的股票代码是"+code+","+"交易所在"+category;
				//return asnwerResult;
			}else if(service.equals("map")){//地图
				//mUnderstanderText.setText(dataJson.toString());
				//JSONObject data = dataJson.getJSONObject("semantic");
				//JSONObject mapdata = data.getJSONObject("slots");
				//String distance = mapdata.getString("distance");//行程
				//JSONObject startLoc = mapdata.getJSONObject("startLoc");
				//String startPoi = startLoc.getString("poi");//起点
				//String startKeyword = startLoc.getString("keyword");
				//JSONObject endLoc = mapdata.getJSONObject("endLoc");
				//String endPoi = endLoc.getString("poi");//终点
				//String endKeyword = endLoc.getString("keyword");
				//asnwerResult = startKeyword+"到"+endKeyword+","+"全程"+distance;
				//asnwerResult = data.toString();
				//return asnwerResult;
			}else if(service.equals("translation")){
				JSONObject  translation = dataJson.getJSONObject("semantic");
				JSONObject jsonObject = translation.getJSONObject("slots");
				String from = jsonObject.getString("source");
				String to = jsonObject.getString("target");
				String content = jsonObject.getString("content");
				MyApplication.fromTranslate = from;
				MyApplication.toTranslate = to;
				MyApplication.contentTranslate = content;
				asnwerResult = "translation";
				
			}else if(service.equals("music")){
				JSONObject data = dataJson.getJSONObject("data");
				JSONArray musicdata = data.getJSONArray("result");
				JSONObject music = musicdata.getJSONObject(0);
				
				String singer = music.getString("singer");
				String sourceName = music.getString("sourceName");
				String name = music.getString("name");
				String downloadUrl = music.getString("downloadUrl");
				MyApplication.SINGER = singer;
				MyApplication.MUSIC_NAME = name;
				asnwerResult = downloadUrl!=null?downloadUrl:"抱歉，爱佳暂时找不到这首歌。";
//				if(downloadUrl!=null)
//					asnwerResult = downloadUrl;
//				else
//					asnwerResult="抱歉，爱佳暂时找不到这首歌。";
			}else if(service.equals("website")){//网址搜索
				JSONObject  website = dataJson.getJSONObject("semantic");
				JSONObject websiteObject = website.getJSONObject("slots");
				String name = websiteObject.getString("name");
				String url = websiteObject.getString("url");
				asnwerResult = name+"的网址是"+url;
			}else {
				try {
					JSONObject answer = dataJson.getJSONObject("answer");
					asnwerResult = answer.getString("text");
					//return asnwerResult;
				} catch (Exception e) {
					//return asnwerResult;
				}
			}
			return asnwerResult;
			
		} catch (JSONException e) {
			e.printStackTrace();
			return asnwerResult;
		} catch (ParseException e) {
			e.printStackTrace();
			return asnwerResult;
		}
	}

	/**
	 * 把yyyy-MM-dd HH:mm:ss可是的时间字符串转换成string类型
	 * 
	 * */
	@SuppressLint("SimpleDateFormat")
	public static String convertTotime(long mill) {
		//Date date = new Date(mill * 1000);
		Date date = new Date(mill);
		String strs = "";
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
			strs = sdf.format(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strs;
	}
	@SuppressLint("SimpleDateFormat")
	public static long getTimelong(String time) throws ParseException {
		SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd");
		Date date=simpleDateFormat .parse(time);
		return date.getTime();
	}
}

